package redisson.rest;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Random;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@RestController
@RequestMapping("/long")
@EnableScheduling
public class AtomicLongController implements SmartInitializingSingleton {

	static Random random = new Random();

	@Autowired
	RedissonClient redissonClient;

	@GetMapping("/next")
	public String next() {

		String now = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
		RAtomicLong atomicLong = redissonClient.getAtomicLong("global:" + now);

		int count = random.nextInt(999);
		log.info("### 产生count -> {} ", count);
		for (int i = 0; i < count; i++) {
			atomicLong.incrementAndGet();
		}
		return String.valueOf(atomicLong.get());
	}

	@Scheduled(cron = "5 0 0 * * *")
	void scheduler() {
		String now = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
		Integer idx = Integer.valueOf(now);
		for (int i = idx - 3; i < idx; i++) {
			RAtomicLong atomicLong = redissonClient.getAtomicLong("global:" + i);
			boolean delete = atomicLong.delete();

			if (delete) {
				log.info("### 删除已过期的key --> {}", i);
			} else {
				log.info("### key不存在，跳过 --> {}", i);
			}
		}

	}

	@Override
	public void afterSingletonsInstantiated() {
		scheduler();
	}

}
